const express = require('express');
const router = express.Router();
const WebSocket = require('ws');
const multiparty = require('multiparty');
const { userModel, messageModel } = require('../model/model');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/login', async (req, res) => {
  let { username, password } = req.body;
  let user = await userModel.findOne({ username, password });
  if (user) {
    res.send({
      code: 200,
      user
    });
  } else {
    res.send({
      code: 500
    });
  }
});

// WebSocket 服务器
const wss = new WebSocket.Server({ port: 3001 });
wss.on('connection', (ws) => {
  ws.send(JSON.stringify({ code: 200, message: '连接成功' }));
  
  ws.on('message', async (message) => {
    const msg = JSON.parse(message);
    
    // 保存消息到数据库
    const newMessage = new messageModel({
      receiverId: msg.receiverId,
      senderId: msg.senderId,
      content: msg.content
    });
    
    await newMessage.save();
    
    // 广播消息给所有连接的客户端
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(msg));
      }
    });
  });
});

router.get('/users', async (req, res) => {
  let { userId } = req.query;
  let data = await userModel.find();
  let list = data.filter(v => v._id.toString() !== userId);
  res.send({
    code: 200,
    list
  });
});

router.get('/messages/history', async (req, res) => {
  const { receiverId, senderId } = req.query;

  const messages = await messageModel.find({
    $or: [
      { receiverId, senderId },
      { receiverId: senderId, senderId: receiverId } // corrected
    ]
  }).sort({ timestamp: 1 }); // 按时间戳排序
  console.log(messages);
  
  res.send({
    code: 200,
    messages
  });
});




router.post('/upload', (req, res) => {
  const form = new multiparty.Form();
  form.uploadDir = './upload';
  form.parse(req, (err, fields, files) => {
    res.send({
      path: 'http://127.0.0.1:3000/' + files.file[0].path
    });
  });
});

module.exports = router;
